import {SimpleProtocol} from "./simple-protocol.mjs";

export class ProtocolDecode {

    constructor() {
        this.buffer = Buffer.alloc(0);
    }

    parse() {
        // 确保数据长度至少包含头部信息
        const headerLength = 46; // 4(length) + 4(magic) + 1(type) + 1(status) + 32(sessionID) + 4(uriLength)
        if (this.buffer.length < headerLength) {
            return null;
        }

        // 读取数据包总长度
        const totalLength = this.buffer.readInt32BE(0);

        // 检查是否收到完整的数据包
        if (this.buffer.length < totalLength + 4) { // +4 因为length字段不包含在totalLength中
            return null;
        }

        // 校验魔数
        const magic = this.buffer.readInt32BE(4);
        if (magic !== SimpleProtocol.MAGIC_NUMBER) {
            throw new Error('Invalid magic number');
        }

        // 解析各个字段
        const type = this.buffer.readUInt8(8);// 类型
        const status = this.buffer.readUInt8(9);// 状态
        const sessionID = this.buffer.toString('utf8', 10, 42);
        const uriLength = this.buffer.readInt32BE(42);
        const uri = this.buffer.toString('utf8', 46, 46 + uriLength);
        // 解析数据内容
        const data = this.buffer.subarray(46 + uriLength, totalLength + 4).toString('utf8');

        // 创建Protocol对象
        const protocol = new SimpleProtocol(type,status,sessionID,uri,data)

        // 更新buffer，移除已处理的数据包
        this.buffer = this.buffer.subarray(totalLength + 4);
        return protocol;
    }

    append(chunk) {
        this.buffer = Buffer.concat([this.buffer, chunk]);
    }
}